<?php
class ModelAccountOrder extends Model {

			public function getAllOrders($start = 0, $limit = 20) {
				if ($start < 0) {
					$start = 0;
				}

				if ($limit < 1) {
					$limit = 1;
				}

				$query = $this->db->query("SELECT o.order_id, o.firstname, o.lastname, os.name as status, o.date_added, o.total, o.currency_code, o.currency_value FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.order_status_id > '0' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.order_id DESC LIMIT " . (int)$start . "," . (int)$limit);

				return $query->rows;
			}

			public function getOrdersByUser($customer_id) {

				$query = $this->db->query("SELECT o.order_id, o.firstname, o.lastname, os.name as status, o.date_added, o.total, o.currency_code, o.currency_value FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.customer_id = '" . (int)$customer_id . "' AND o.order_status_id > '0' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.order_id DESC");

				return $query->rows;
			}

			public function getOrdersByFilter($data = array()) {
				$sql = "SELECT o.*, CONCAT(o.firstname, ' ', o.lastname) AS customer,
				            payment_country.iso_code_2 as pc_iso_code_2,
				            payment_country.iso_code_3 as pc_iso_code_3,
                            shipping_country.iso_code_2 as sc_iso_code_2,
				            shipping_country.iso_code_3 as sc_iso_code_3,
				            payment_zone.code as payment_zone_code,
				            shipping_zone.code as shipping_zone_code

				        FROM `" . DB_PREFIX . "order` o
				        LEFT JOIN `" . DB_PREFIX . "country` payment_country ON ( payment_country.country_id = o.payment_country_id)
				        LEFT JOIN `" . DB_PREFIX . "country` shipping_country ON ( shipping_country.country_id = o.shipping_country_id)
				        LEFT JOIN `" . DB_PREFIX . "zone` payment_zone ON ( payment_zone.zone_id = o.payment_zone_id)
				        LEFT JOIN `" . DB_PREFIX . "zone` shipping_zone ON ( shipping_zone.zone_id = o.shipping_zone_id)
				                    ";

				if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) {
					$sql .= " WHERE o.order_status_id IN ( ". $this->db->escape(rtrim($data['filter_order_status_id'],",")) . ")";
				} else {
					$sql .= " WHERE o.order_status_id > '0'";
				}

				if (!empty($data['filter_order_id'])) {
					$sql .= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'";
				}

				if (!empty($data['filter_customer'])) {
					$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
				}


				if (!empty($data['filter_date_added_to']) && !empty($data['filter_date_added_from'])) {

					$sql .= " AND o.date_added BETWEEN STR_TO_DATE('" . $this->db->escape($data['filter_date_added_from']) . "','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE('" . $this->db->escape($data['filter_date_added_to']) . "','%Y-%m-%d %H:%i:%s')";

				} elseif (!empty($data['filter_date_added_from'])) {

					$sql .= " AND o.date_added >= STR_TO_DATE('" . $this->db->escape($data['filter_date_added_from']) . "','%Y-%m-%d %H:%i:%s')";

				} elseif (!empty($data['filter_date_added_on'])) {

					$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added_on']) . "')";
				}

				if (!empty($data['filter_date_modified_to']) && !empty($data['filter_date_modified_from'])) {

					$sql .= " AND o.date_modified BETWEEN STR_TO_DATE('" . $this->db->escape($data['filter_date_modified_from']) . "','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE('" . $this->db->escape($data['filter_date_modified_to']) . "','%Y-%m-%d %H:%i:%s')";

				} elseif (!empty($data['filter_date_modified_from'])) {

					$sql .= " AND o.date_modified >= STR_TO_DATE('" . $this->db->escape($data['filter_date_modified_from']) . "','%Y-%m-%d %H:%i:%s')";

				} elseif (!empty($data['filter_date_modified_on'])) {

					$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified_on']) . "')";
				}


				if (!empty($data['filter_total'])) {
					$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
				}

				$sort_data = array(
					'o.order_id',
					'customer',
					'o.date_added',
					'o.date_modified',
					'o.total'
				);

				if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
					$sql .= " ORDER BY " . $data['sort'];
				} else {
					$sql .= " ORDER BY o.order_id";
				}

				if (isset($data['order']) && ($data['order'] == 'DESC')) {
					$sql .= " DESC";
				} else {
					$sql .= " ASC";
				}

				if (isset($data['start']) || isset($data['limit'])) {
					if ($data['start'] < 0) {
						$data['start'] = 0;
					}

					if ($data['limit'] < 1) {
						$data['limit'] = 20;
					}

					$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
				}

                $orders_query = $this->db->query($sql);
                $orders = array();
                $index = 0;

                $this->load->model('localisation/language');

                foreach ($orders_query->rows as $order) {

                    $payment_iso_code_2 = '';
                    $payment_iso_code_3 = '';

                    if (isset($order["pc_iso_code_2"])) {
                        $payment_iso_code_2 = $order["pc_iso_code_2"];
                    }

                    if (isset($order["pc_iso_code_3"])) {
                        $payment_iso_code_3 = $order["pc_iso_code_3"];
                    }

                    $shipping_iso_code_2 = '';
                    $shipping_iso_code_3 = '';

                    if (isset($order["sc_iso_code_2"])) {
                        $shipping_iso_code_2 = $order["sc_iso_code_2"];
                    }

                    if (isset($order["sc_iso_code_3"])) {
                        $shipping_iso_code_3 = $order["sc_iso_code_3"];
                    }

                    if (isset($order["payment_zone_code"])) {
                        $payment_zone_code = $order["payment_zone_code"];
                    } else {
                        $payment_zone_code = '';
                    }

                    if (isset($order["shipping_zone_code"])) {
                        $shipping_zone_code = $order["shipping_zone_code"];
                    } else {
                        $shipping_zone_code = '';
                    }


                    $language_info = $this->model_localisation_language->getLanguage($order['language_id']);

                    if ($language_info) {
                        $language_code = $language_info['code'];
                        $language_filename = $language_info['filename'];
                        $language_directory = $language_info['directory'];
                    } else {
                        $language_code = '';
                        $language_filename = '';
                        $language_directory = '';
                    }

                    $orders[$index] =  array(
                    'order_id'                => $order['order_id'],
                    'invoice_no'              => $order['invoice_no'],
                    'invoice_prefix'          => $order['invoice_prefix'],
                    'store_id'                => $order['store_id'],
                    'store_name'              => $order['store_name'],
                    'store_url'               => $order['store_url'],
                    'customer_id'             => $order['customer_id'],
                    'firstname'               => $order['firstname'],
                    'lastname'                => $order['lastname'],
                    'telephone'               => $order['telephone'],
                    'fax'                     => $order['fax'],
                    'email'                   => $order['email'],
                    'payment_firstname'       => $order['payment_firstname'],
                    'payment_lastname'        => $order['payment_lastname'],
                    'payment_company'         => $order['payment_company'],
                    //'payment_company_id'      => $order['payment_company_id'],
                    //'payment_tax_id'          => $order['payment_tax_id'],
                    'payment_address_1'       => $order['payment_address_1'],
                    'payment_address_2'       => $order['payment_address_2'],
                    'payment_postcode'        => $order['payment_postcode'],
                    'payment_city'            => $order['payment_city'],
                    'payment_zone_id'         => $order['payment_zone_id'],
                    'payment_zone'            => $order['payment_zone'],
                    'payment_zone_code'       => $payment_zone_code,
                    'payment_country_id'      => $order['payment_country_id'],
                    'payment_country'         => $order['payment_country'],
                    'payment_iso_code_2'      => $payment_iso_code_2,
                    'payment_iso_code_3'      => $payment_iso_code_3,
                    'payment_address_format'  => $order['payment_address_format'],
                    'payment_method'          => $order['payment_method'],
                    'payment_code'            => $order['payment_code'],
                    'shipping_firstname'      => $order['shipping_firstname'],
                    'shipping_lastname'       => $order['shipping_lastname'],
                    'shipping_company'        => $order['shipping_company'],
                    'shipping_address_1'      => $order['shipping_address_1'],
                    'shipping_address_2'      => $order['shipping_address_2'],
                    'shipping_postcode'       => $order['shipping_postcode'],
                    'shipping_city'           => $order['shipping_city'],
                    'shipping_zone_id'        => $order['shipping_zone_id'],
                    'shipping_zone'           => $order['shipping_zone'],
                    'shipping_zone_code'      => $shipping_zone_code,
                    'shipping_country_id'     => $order['shipping_country_id'],
                    'shipping_country'        => $order['shipping_country'],
                    'shipping_iso_code_2'     => $shipping_iso_code_2,
                    'shipping_iso_code_3'     => $shipping_iso_code_3,
                    'shipping_address_format' => $order['shipping_address_format'],
                    'shipping_method'         => $order['shipping_method'],
                    'shipping_code'           => $order['shipping_code'],
                    'comment'                 => $order['comment'],
                    'total'                   => $order['total'],
                    'order_status_id'         => $order['order_status_id'],
                    'language_id'             => $order['language_id'],
                    'language_code'           => $language_code,
                    'language_filename'       => $language_filename,
                    'language_directory'      => $language_directory,
                    'currency_id'             => $order['currency_id'],
                    'currency_code'           => $order['currency_code'],
                    'currency_value'          => $order['currency_value'],
                    'ip'                      => $order['ip'],
                    'forwarded_ip'            => $order['forwarded_ip'],
                    'user_agent'              => $order['user_agent'],
                    'accept_language'         => $order['accept_language'],
                    'date_modified'           => $order['date_modified'],
                    'date_added'              => $order['date_added']
                    );
                    $index++;
                }

                return $orders;
            }

            public function getOrderStatuses() {

                $query = $this->db->query("SELECT order_status_id, name FROM " . DB_PREFIX . "order_status WHERE language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY name");

                return $query->rows;
            }

        public function getOrderOptionsMod($order_id, $order_product_id) {
            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option
             LEFT JOIN " . DB_PREFIX . "product_option_value pov ON (" . DB_PREFIX . "order_option.product_option_value_id = pov.product_option_value_id)
            WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'");

            return $query->rows;
        }

        public function getOrderHistoriesRest($order_id) {
            $query = $this->db->query("SELECT oh.date_added, os.name AS status, oh.comment, oh.notify FROM " . DB_PREFIX . "order_history oh LEFT JOIN " . DB_PREFIX . "order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added ASC");

            return $query->rows;
        }

        public function getOrderStatusById($order_id) {
            $query = $this->db->query("SELECT order_status_id AS status FROM " . DB_PREFIX . "order WHERE order_id = '" . (int)$order_id . "'");

            return $query->row['status'];
        }

			
	public function getOrder($order_id) {
		$order_query = $this->db->query("SELECT *, os.name AS status FROM `" . DB_PREFIX . "order`o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.order_id = '" . (int)$order_id . "' AND customer_id = '" . (int)$this->customer->getId() . "'");

		if ($order_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");

			if ($country_query->num_rows) {
				$payment_iso_code_2 = $country_query->row['iso_code_2'];
				$payment_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$payment_iso_code_2 = '';
				$payment_iso_code_3 = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");

			if ($zone_query->num_rows) {
				$payment_zone_code = $zone_query->row['code'];
			} else {
				$payment_zone_code = '';
			}

			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");

			if ($country_query->num_rows) {
				$shipping_iso_code_2 = $country_query->row['iso_code_2'];
				$shipping_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$shipping_iso_code_2 = '';
				$shipping_iso_code_3 = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");

			if ($zone_query->num_rows) {
				$shipping_zone_code = $zone_query->row['code'];
			} else {
				$shipping_zone_code = '';
			}

			return array(
				'order_id'                => $order_query->row['order_id'],
				'invoice_no'              => $order_query->row['invoice_no'],
				'invoice_prefix'          => $order_query->row['invoice_prefix'],
				'store_id'                => $order_query->row['store_id'],
				'store_name'              => $order_query->row['store_name'],
				'store_url'               => $order_query->row['store_url'],
				'customer_id'             => $order_query->row['customer_id'],
				'fullname'               => $order_query->row['fullname'],
				'telephone'               => $order_query->row['telephone'],
				'fax'                     => $order_query->row['fax'],
				'email'                   => $order_query->row['email'],
				'payment_fullname'       => $order_query->row['payment_fullname'],
				'payment_company'         => $order_query->row['payment_company'],
				'payment_address'       => $order_query->row['payment_address'],
				'payment_postcode'        => $order_query->row['payment_postcode'],
				'payment_city'            => $order_query->row['payment_city'],
				'payment_zone_id'         => $order_query->row['payment_zone_id'],
				'payment_zone'            => $order_query->row['payment_zone'],
				'payment_zone_code'       => $payment_zone_code,
				'payment_country_id'      => $order_query->row['payment_country_id'],
				'payment_country'         => $order_query->row['payment_country'],
				'payment_iso_code_2'      => $payment_iso_code_2,
				'payment_iso_code_3'      => $payment_iso_code_3,
				'payment_address_format'  => $order_query->row['payment_address_format'],
				'payment_method'          => $order_query->row['payment_method'],
				'shipping_fullname'      => $order_query->row['shipping_fullname'],
				'shipping_company'        => $order_query->row['shipping_company'],
				'shipping_address'      => $order_query->row['shipping_address'],
				'shipping_postcode'       => $order_query->row['shipping_postcode'],
				'shipping_telephone'       => $order_query->row['shipping_telephone'],
				'shipping_city'           => $order_query->row['shipping_city'],
				'shipping_zone_id'        => $order_query->row['shipping_zone_id'],
				'shipping_zone'           => $order_query->row['shipping_zone'],
				'shipping_zone_code'      => $shipping_zone_code,
				'shipping_country_id'     => $order_query->row['shipping_country_id'],
				'shipping_country'        => $order_query->row['shipping_country'],
				'shipping_iso_code_2'     => $shipping_iso_code_2,
				'shipping_iso_code_3'     => $shipping_iso_code_3,
				'shipping_address_format' => $order_query->row['shipping_address_format'],
				'shipping_method'         => $order_query->row['shipping_method'],
				'comment'                 => $order_query->row['comment'],
				'is_pay'               => $order_query->row['is_pay'],
				'total'                   => $order_query->row['total'],
				'order_status_id'         => (int)$order_query->row['order_status_id']?$order_query->row['order_status_id']:16,
				'language_id'             => $order_query->row['language_id'],
				'currency_id'             => $order_query->row['currency_id'],
				'currency_code'           => $order_query->row['currency_code'],
				'currency_value'          => $order_query->row['currency_value'],
				'date_modified'           => $order_query->row['date_modified'],
				'date_added'              => $order_query->row['date_added'],
				'ip'                      => $order_query->row['ip'],
        		'status'                  => !empty($order_query->row['status'])?$order_query->row['status']:'无效',
    			'bill_status'             => $order_query->row['bill_status'],
    			'is_pay'                  => $order_query->row['is_pay']
			);
		} else {
			return false;
		}
	}

  public function getOrderWithStatusZero($order_id) {
    $order_query = $this->db->query("SELECT *, os.name AS status FROM `" . DB_PREFIX . "order`o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.order_id = '" . (int)$order_id . "' AND customer_id = '" . (int)$this->customer->getId() . "'");

    if ($order_query->num_rows) {
      $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");

      if ($country_query->num_rows) {
        $payment_iso_code_2 = $country_query->row['iso_code_2'];
        $payment_iso_code_3 = $country_query->row['iso_code_3'];
      } else {
        $payment_iso_code_2 = '';
        $payment_iso_code_3 = '';
      }

      $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");

      if ($zone_query->num_rows) {
        $payment_zone_code = $zone_query->row['code'];
      } else {
        $payment_zone_code = '';
      }

      $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");

      if ($country_query->num_rows) {
        $shipping_iso_code_2 = $country_query->row['iso_code_2'];
        $shipping_iso_code_3 = $country_query->row['iso_code_3'];
      } else {
        $shipping_iso_code_2 = '';
        $shipping_iso_code_3 = '';
      }

      $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");

      if ($zone_query->num_rows) {
        $shipping_zone_code = $zone_query->row['code'];
      } else {
        $shipping_zone_code = '';
      }

      return array(
        'order_id'                => $order_query->row['order_id'],
        'invoice_no'              => $order_query->row['invoice_no'],
        'invoice_prefix'          => $order_query->row['invoice_prefix'],
        'store_id'                => $order_query->row['store_id'],
        'store_name'              => $order_query->row['store_name'],
        'store_url'               => $order_query->row['store_url'],
        'customer_id'             => $order_query->row['customer_id'],
        'fullname'               => $order_query->row['fullname'],
        'telephone'               => $order_query->row['telephone'],
        'fax'                     => $order_query->row['fax'],
        'email'                   => $order_query->row['email'],
        'payment_fullname'       => $order_query->row['payment_fullname'],
        'payment_company'         => $order_query->row['payment_company'],
        'payment_address'       => $order_query->row['payment_address'],
        'payment_postcode'        => $order_query->row['payment_postcode'],
        'payment_city'            => $order_query->row['payment_city'],
        'payment_zone_id'         => $order_query->row['payment_zone_id'],
        'payment_zone'            => $order_query->row['payment_zone'],
        'payment_zone_code'       => $payment_zone_code,
        'payment_country_id'      => $order_query->row['payment_country_id'],
        'payment_country'         => $order_query->row['payment_country'],
        'payment_iso_code_2'      => $payment_iso_code_2,
        'payment_iso_code_3'      => $payment_iso_code_3,
        'payment_address_format'  => $order_query->row['payment_address_format'],
        'payment_method'          => $order_query->row['payment_method'],
        'shipping_fullname'      => $order_query->row['shipping_fullname'],
        'shipping_company'        => $order_query->row['shipping_company'],
        'shipping_address'      => $order_query->row['shipping_address'],
        'shipping_postcode'       => $order_query->row['shipping_postcode'],
        'shipping_telephone'       => $order_query->row['shipping_telephone'],
        'shipping_city'           => $order_query->row['shipping_city'],
        'shipping_zone_id'        => $order_query->row['shipping_zone_id'],
        'shipping_zone'           => $order_query->row['shipping_zone'],
        'shipping_zone_code'      => $shipping_zone_code,
        'shipping_country_id'     => $order_query->row['shipping_country_id'],
        'shipping_country'        => $order_query->row['shipping_country'],
        'shipping_iso_code_2'     => $shipping_iso_code_2,
        'shipping_iso_code_3'     => $shipping_iso_code_3,
        'shipping_address_format' => $order_query->row['shipping_address_format'],
        'shipping_method'         => $order_query->row['shipping_method'],
        'comment'                 => $order_query->row['comment'],
        'total'                   => $order_query->row['total'],
        'order_status_id'         => $order_query->row['order_status_id'],
        'language_id'             => $order_query->row['language_id'],
        'currency_id'             => $order_query->row['currency_id'],
        'currency_code'           => $order_query->row['currency_code'],
        'currency_value'          => $order_query->row['currency_value'],
        'date_modified'           => $order_query->row['date_modified'],
        'date_added'              => $order_query->row['date_added'],
        'ip'                      => $order_query->row['ip'],
        'status'                      => $order_query->row['status'],
        'bill_status'                     => $order_query->row['bill_status'],
      );
    } else {
      return false;
    }
  }

	public function getOrders($start = 0, $limit = 20) {
		if ($start < 0) {
			$start = 0;
		}

		if ($limit < 1) {
			$limit = 1;
		}

		$query = $this->db->query("SELECT o.is_pay,o.payment_code,o.payment_method,o.order_id, o.id_code, o.fullname, o.order_status_id, os.name as status, o.date_added, o.total, o.currency_code, o.currency_value FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.customer_id = '" . (int)$this->customer->getId() . "' AND o.store_id = '" . (int)$this->config->get('config_store_id') . "' AND o.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.order_id DESC LIMIT " . (int)$start . "," . (int)$limit);

		$results = $query->rows;

		foreach ($results as $key => $result) {
			$results[$key]['order_status_id'] = (int)$result['order_status_id']?$result['order_status_id']:16;
			$results[$key]['status'] = !empty($result['status'])?$result['status']:'无效';
		}

		return $results;
	}

	public function getPeriods($start = 0, $limit = 20) {
		if ($start < 0) {
			$start = 0;
		}

		if ($limit < 1) {
			$limit = 1;
		}

		$query = $this->db->query("SELECT o.is_pay,o.order_id, o.fullname, o.order_status_id, os.name as status, o.date_added, o.total, o.currency_code, o.currency_value FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.customer_id = '" . (int)$this->customer->getId() . "' AND o.payment_code = 'magfin' AND o.order_status_id > '0' AND o.store_id = '" . (int)$this->config->get('config_store_id') . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.order_id DESC LIMIT " . (int)$start . "," . (int)$limit);

		return $query->rows;
	}

	public function getOrderProduct($order_id, $order_product_id) {	
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'");

		return $query->row;
	}

	public function getOrderProducts($order_id) {
		 // $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'")->rows;
		$op = M('order_product');
		$where['order_id'] = $order_id;
		$query = $op
		->alias('op')
		->join('LEFT JOIN review r ON r.order_product_id = op.order_product_id')
		->where($where)
		->field('op.order_product_id,order_id,op.product_id,op.name,op.model,op.quantity,op.price,op.tax,op.total,r.review_id')
		->select();

		return $query;
	}

	public function getOrderOptions($order_id, $order_product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'");

		return $query->rows;
	}

	public function getOrderVouchers($order_id) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_voucher` WHERE order_id = '" . (int)$order_id . "'");

		return $query->rows;
	}

	public function getOrderTotals($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order");

		return $query->rows;
	}

	public function getOrderHistories($order_id) {
		$query = $this->db->query("SELECT date_added, os.name AS status, oh.comment, oh.notify FROM " . DB_PREFIX . "order_history oh LEFT JOIN " . DB_PREFIX . "order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added");

		return $query->rows;
	}

	public function getTotalOrders() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` o WHERE customer_id = '" . (int)$this->customer->getId() . "' AND o.order_status_id > '0' AND o.store_id = '" . (int)$this->config->get('config_store_id') . "'");

		return $query->row['total'];
	}

	public function getTotalPeriods() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` o WHERE customer_id = '" . (int)$this->customer->getId() . "' AND o.payment_code = 'magfin' AND o.order_status_id > '0' AND o.store_id = '" . (int)$this->config->get('config_store_id') . "'");

		return $query->row['total'];
	}

	public function getTotalOrderProductsByOrderId($order_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

		return $query->row['total'];
	}

	public function getTotalOrderVouchersByOrderId($order_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order_voucher` WHERE order_id = '" . (int)$order_id . "'");

		return $query->row['total'];
	}
	public function saveIs_invoice($order_id,$bill_status){

		$order = M('order');
		$data['bill_status'] = $bill_status;
		$where['order_id'] = $order_id;
		$query = $order
		->where($where)
		->data($data)
		->save();
		return $query;
	}

  public function getLuckydraw($order){
    
    if($order['status']=="已退款" || $order['status']=="无效") {
      return false;
    }
    $cur_time = date('Y-m-d H:i:s', time());
    $map['start_time'] = array(array('lt',$cur_time), array('lt',$order['date_added']));
    $map['end_time'] = array(array('gt',$cur_time), array('gt',$order['date_added']));
    $map['status'] = array('eq', 1);
    $luckydraw = M('luckydraw')
      ->where($map)
      ->find();
    if(empty($luckydraw)) {
      return false;
    }
    //是否满足金额条件
    $luckydraw_number = M('luckydraw_number')->where(array('luckydraw_id'=>$luckydraw['luckydraw_id']))->select();
    $time = 0;
    foreach ($luckydraw_number as $number) {
      if($order['total']>=$number['amount'] && $time<$number['number']) {
        $time = $number['number'];
      } 
    }
    if($time<=0) {
      return false;
    }
    //是否已经抽过
    $map = array();
    $map['luckydraw_id'] = array('eq', $luckydraw['luckydraw_id']);
    $map['order_id'] = array('eq', $order['order_id']);
    $luckydrawed_times = M('luckydraw_history')->where($map)->count();
    $real_time = $time - $luckydrawed_times;
    if($real_time<=0) {
      // return false;
    }
    //是否已经抽中过奖品
    $map = array();
    $map['lh.luckydraw_id'] = array('eq', $luckydraw['luckydraw_id']);
    $map['lh.order_id'] = array('eq', $order['order_id']);
    $map['lh.hit'] = 1;
    $hitted_prices = M('luckydraw_history lh')
    ->join('LEFT JOIN luckydraw_product lp ON lh.luckydraw_product_id = lp.luckydraw_product_id')->where($map)->select();
    //奖品配置
    $map = array();
    $map['luckydraw_id'] = array('eq', $luckydraw['luckydraw_id']);
    $luckydraw_product = M('luckydraw_product')->where($map)->order('sort_order ASC')->select();
    //返回抽奖id和抽奖次数
    $ret = array();
    $ret['luckydraw_id'] = $luckydraw['luckydraw_id'];
    $ret['left_times'] = $real_time;
    $ret['hitted_prices'] = $hitted_prices;
    $ret['products'] = $luckydraw_product;
    return $ret;
  }

  public function drawPrice($order_id,$total,$luckydraw_id,$times) {

    //获取还剩余的奖品
    $map['luckydraw_id'] = array('eq', $luckydraw_id);
    $luckydraw = M('luckydraw')
      ->where($map)
      ->find();
	
	$try = rand(1, 100);
    if($try > $luckydraw['chance']) {
      //插入抽取历史
      $data = array();
      $data['luckydraw_id'] = $luckydraw_id;
      $data['customer_id'] = $this->customer->getId();
      $data['order_id'] = $order_id;
      $data['hit'] = 0;
      $data['luckydraw_product_id'] = 0;
      $data['date_added'] = date('Y-m-d H:i:s', time());
      M('luckydraw_history')->data($data)->add();
      return array('item'=>0);
    }

    $map['luckydraw_id'] = array('eq', $luckydraw_id);
    $luckydraw_product = M('luckydraw_product')->where($map)->order('sort_order ASC')->select();
    $luckydraw_history_query = $this->db->query("SELECT luckydraw_product_id, SUM(hit) AS hit_number FROM " . DB_PREFIX . "luckydraw_history WHERE luckydraw_id = '" . (int)$luckydraw_id . "' GROUP BY luckydraw_product_id");
    $luckydraw_hits = $luckydraw_history_query->rows;

    $product_qty = array();
    foreach ($luckydraw_product as $lp) {
      $product_qty[$lp['luckydraw_product_id']] = $lp['quantity'];
    }
    foreach ($luckydraw_hits as $lh) {
      $product_qty[$lh['luckydraw_product_id']] = $product_qty[$lh['luckydraw_product_id']]-$lh['hit_number'];
    }

	$total_price = array_sum($product_qty);
	$try = rand(1, $total_price);
	$item = 0;

	if($luckydraw['hit'] != 0 && $times == 1){ //特殊必中时

		if($total >= 1500 && $total < 3000){
			$hit_price = '28.00元';
			$no = 8;
		}
		else if($total >= 3000 && $total < 5000){
			$hit_price = '58.00元';
			$no = 7;
		}
		else if($total >= 5000 && $total < 8000){
			$hit_price = '108.00元';
			$no = 6;
		}
		else if($total >= 8000 && $total < 10000){
			$hit_price = '168.00元';
			$no = 5;
		}
		else if($total >= 10000){
			$hit_price = '198.00元';
			$no = 4;
		}
		
		$where['product_name'] = $hit_price;
		$where['luckydraw_id'] = $luckydraw_id;
		$hit_product = M('luckydraw_product')->where($where)->getField('luckydraw_product_id');

		$data = array();
		$data['luckydraw_id'] = $luckydraw_id;
		$data['customer_id'] = $this->customer->getId();
		$data['order_id'] = $order_id;
		$data['hit'] = 1;
		$data['luckydraw_product_id'] = $hit_product;
		$data['date_added'] = date('Y-m-d H:i:s', time());
		M('luckydraw_history')->data($data)->add();
		return array('item'=>$no);

	}
	else{ //正常非必中时

		//根据$try判断它属于哪一个奖
		foreach ($product_qty as $luckydraw_product_id => $qty) {
		  $item++;
		  if($try<=$qty) {
			$data = array();
			$data['luckydraw_id'] = $luckydraw_id;
			$data['customer_id'] = $this->customer->getId();
			$data['order_id'] = $order_id;
			$data['hit'] = 1;
			$data['luckydraw_product_id'] = $luckydraw_product_id;
			$data['date_added'] = date('Y-m-d H:i:s', time());
			M('luckydraw_history')->data($data)->add();
			return array('item'=>$item);
		  } else {
			$try = $try-$qty;        
		  }
		}

	}
    
    //如果奖品抽完, 为抽中插入抽取历史
    $data = array();
    $data['luckydraw_id'] = $luckydraw_id;
    $data['customer_id'] = $this->customer->getId();
    $data['order_id'] = $order_id;
    $data['hit'] = 0;
    $data['luckydraw_product_id'] = 0;
    $data['date_added'] = date('Y-m-d H:i:s', time());
    M('luckydraw_history')->data($data)->add();
    return array('item'=>0);
  }
}